package pckg.positionlogger;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class PositionLoggerActivity extends Activity {
    /** Called when the activity is first created. */
    protected PositionInterface positionInterface;
    private boolean isBound = false;
    public static final String PREFS_NAME = "PositionLoggerPrefs";
    /* GUI VARIABLE */
	private Button startServiceButton;
    private Button stopServiceButton;
    private Button updateButton;
    private Button exitButton;
    //Protected variable Declaration
    protected static Location lastLocation;
    //Local Variable Declaration 
    private double latitude;
    private double longitude;
    private double distance;
    private double averageSpeed;
    /* Declare intent to start service */
    private Intent myIntent;
	/*ON CREATE: called when activity is created*/
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      //Initialize Buttons and assign them Listeners
        startServiceButton = (Button) findViewById(R.id.start_service_button);
        startServiceButton.setOnClickListener(startServiceButtonListener);
        stopServiceButton = (Button) findViewById(R.id.stop_service_button);
        stopServiceButton.setOnClickListener(stopServiceButtonListener);
        updateButton = (Button) findViewById(R.id.update_values_button);
        updateButton.setOnClickListener(updateButtonListener);
        exitButton = (Button) findViewById(R.id.exit_button);
        exitButton.setOnClickListener(exitButtonListener);
        /* Initialize the intent to start the service for receiving GPS Data */
        myIntent = new Intent(this, ServiceGPS.class);
    }
     private ServiceConnection myConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            // This is called when the connection with the service has been
            // established, giving us the service object we can use to
            // interact with the service.  Because we have bound to a explicit
            // service that we know is running in our own process, we can
            // cast its IBinder to a concrete class and directly access it.
        	positionInterface = PositionInterface.Stub.asInterface(service);
        }
        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            // Because it is running in our same process, we should never
            // see this happen.
            positionInterface = null;
        }
    };
    //Binding the service
    void doBindService() {  
    	// Establish a connection with the service.  We use an explicit
    	// class name because we want a specific service implementation that
    	// we know will be running in our own process (and thus won't be
    	// supporting component replacement by other applications).		
		bindService(myIntent, myConnection, Context.BIND_AUTO_CREATE);
		isBound = true;				
	}
    //UnBind the service
    void doUnbindService() {
    	unbindService(myConnection);
    	isBound = false;
	}
    //Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. 
    public void onPause(){
    	super.onPause();    	
    	// We need an Editor object to make preference changes.
        // All objects are from android.context.Context
        SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("serviceConnected", isBound);
        // Commit the edits!
        editor.commit();        
        if(isBound){
        	doUnbindService();  //must unbind it before pausing activity
        }
    }
    //Called after onPause(), for activity to start interacting with the user
    public void onResume(){
    	super.onResume();
    	SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
        isBound = sharedPreferences.getBoolean("serviceConnected", false); //checks if service is running        														  
        														  //"false" is the default return value
        													  
        if(isBound){			//if service is running
        	doBindService();	//bind it
        	updateValues();		//and update the activity's variables
        }
        
    }
    /****************************************************************************
	 * 				BUTTON LISTENERS AND THEIR CALLBACKS
	 * **************************************************************************/
    /* ******************* Implementation of START SERVICE BUTTON ************************/
    private OnClickListener startServiceButtonListener = new OnClickListener() {
        public void onClick(View v) {     
        	//Checking the Status of Service.
        	if(isBound){
        		Toast toast = Toast.makeText(getApplicationContext(), 
    					"Service already running.", Toast.LENGTH_SHORT);
    			toast.show();       		
        	}
        	else{
        		//if Service is not already running .RUN the services
        		startService(myIntent);
        		doBindService();        	
        		//Initialization and declaration of Location Manager Object
        		LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        		//Check for the GPS Status
        		boolean GpsEnabled = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        		//Check for the SDCard existence
        		boolean SdPresent = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
	        	//Checking GPS and SD Card Status 
        		if(!GpsEnabled || !SdPresent){ //GPS not Enabled/SD Card not found
	        		if(!GpsEnabled){ //GPS not Enabled
	        			if(!SdPresent){ //SD Card not found
	        				Toast toast = Toast.makeText(getApplicationContext(), 
	        	        			"GPS is disabled.\n SD Card not found", 
	        	        			Toast.LENGTH_SHORT);
	        	        	toast.show();
	        			} else {
	        				Toast toast = Toast.makeText(getApplicationContext(), 
	        	        			"GPS is disabled.", 
	        	        			Toast.LENGTH_SHORT);
	        	        	toast.show();
	        				
	        			}
	        		} else {
	        			Toast toast = Toast.makeText(getApplicationContext(), 
	    	        			"SD Card not found", 
	    	        			Toast.LENGTH_SHORT);
	    	        	toast.show();
	        		}
	        		
	        	}
        	}
        }
    };
    /* ******************* Implementation of STOP SERVICE BUTTON ************************/
    private OnClickListener stopServiceButtonListener = new OnClickListener() {
        public void onClick(View v) {
        	//Checking status of Services
        	if(isBound){
        		doUnbindService();
        		stopService(myIntent);      
        	} else {
        		Toast toast = Toast.makeText(getApplicationContext(), 
    					"Service already stopped.", Toast.LENGTH_SHORT);
    			toast.show();
        	}
        }
    };
    /* ******************* Implementation of UPDATE SERVICE BUTTON ************************/   
    private OnClickListener updateButtonListener = new OnClickListener() {
        public void onClick(View v) {
        		updateValues();//Update the values 
        		writeValues();//Write the values 
        }
    };
    /* ******************* Implementation of EXIT SERVICE BUTTON ************************/
    private OnClickListener exitButtonListener = new OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    };
    //Writing values to TextView  
    public void writeValues(){
    	TextView tviewLongitude = (TextView) findViewById(R.id.longitude_text);
    	tviewLongitude.setText(Double.toString(longitude));
    	
    	TextView tviewLatitude = (TextView) findViewById(R.id.latitude_text);
    	tviewLatitude.setText(Double.toString(latitude));
    	
    	TextView tviewDistance = (TextView) findViewById(R.id.distance_text);
    	tviewDistance.setText(Double.toString(distance));
    	
    	TextView tviewAverageSpeed = (TextView) findViewById(R.id.avg_speed_text);
    	tviewAverageSpeed.setText(Double.toString(averageSpeed)); 
    }
    //Update the values for lat,lon,distance and avgspeed 
    public void updateValues(){
    	if(positionInterface != null){
    		try {
    			latitude = positionInterface.getLatitude();
        		longitude = positionInterface.getLongitude();
        		distance = positionInterface.getDistance();
        		averageSpeed = positionInterface.getAverageSpeed();
    		} catch (RemoteException e) {
    			e.printStackTrace();
    		}
    	}
    }
	
}